<template>
  <div>
    <Search></Search>
    <GoodsListNav></GoodsListNav>
    <div class="goods-list-container">
      <Alert show-icon class="tips-box">
        小提示
        <Icon type="ios-lightbulb-outline" slot="icon"></Icon>
        <template slot="desc"
          >点击商品下方的优惠券与促销活动，结算更便宜哦。</template
        >
      </Alert>
      <Table
        :loading="loading"
        border
        :columns="columns"
        :data="shoppingCart"
        size="large"
        no-data-text="请稍等，正在加载中~"
      ></Table>
      <!-- 优惠券 -->
      <div class="address-container">
        <h3>优惠信息</h3>
        <div class="address-box">
          <div class="address-check">
            <div class="address-check-name">
              <span
                ><Icon type="ios-checkmark-outline"></Icon>
                {{ checkCoupon.choose }}</span
              >
            </div>
            <div class="address-detail">
              <p>{{ checkCoupon.name }}</p>
            </div>
          </div>
          <Collapse>
            <Panel>
              选择优惠
              <p slot="content">
                <RadioGroup vertical size="large" @on-change="changeCoupon">
                  <Radio
                    v-for="(item, index) in coupons"
                    :key="index"
                    :label="index"
                  >
                    <span>
                      {{ item.couponName }}: {{ item.threshold }}-
                      {{ item.discount_price }}
                    </span>
                  </Radio>
                </RadioGroup>
              </p>
            </Panel>
          </Collapse>
        </div>
      </div>
      <!-- 促销 -->
      <div class="address-container">
        <h3>促销信息</h3>
        <div class="address-box">
          <div class="address-check">
            <div class="address-check-name">
              <span
                ><Icon type="ios-checkmark-outline"></Icon>
                {{ checkPromotion.choose }}</span
              >
            </div>
            <div class="address-detail">
              <p>{{ checkPromotion.name }}</p>
            </div>
          </div>
          <Collapse>
            <Panel>
              选择促销活动
              <p slot="content">
                <RadioGroup vertical size="large" @on-change="changePromotion">
                  <Radio
                    v-for="(item, index) in promotions"
                    :key="index"
                    :label="item"
                  >
                    <span>
                      {{ item }}
                    </span>
                  </Radio>
                </RadioGroup>
              </p>
            </Panel>
          </Collapse>
        </div>
      </div>
      <div class="remarks-container">
        <h3>备注</h3>
        <i-input
          v-model="remarks"
          size="large"
          placeholder="在这里填写备注信息"
          class="remarks-input"
        ></i-input>
      </div>
      <div class="pay-container">
        <div class="pay-box">
          <p>
            <span>提交订单应付总额：</span>
            <span class="money"
              ><Icon type="social-yen"></Icon> {{ totalPrice }}</span
            >
          </p>
          <div class="pay-btn">
            <Button type="error" size="large" @click="gotoPay">支付订单</Button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Search from '~/components/search/Search'
import GoodsListNav from '~/components/nav/GoodsListNav'
import { getGoodsBatch, deleteShoppingCart } from '~/api/cart'
import { getOrding, deleteOrding } from '~/api/order'
import { queryCoupon, queryPromotion, usePromotion } from '~/api/couponAndPromotions'
import { generateOrder } from '~/api/orderLocal'
export default {
  name: 'Order',
  beforeRouteEnter(to, from, next) {
    if (process.client) {
      window.scrollTo(0, 0)
    }
    next()
  },
  data() {
    return {
      // 表格渲染依据
      columns: [
        {
          title: '标题',
          width: 500,
          align: 'center',
          render: (h, params) => {
            let resultStr = ''
            resultStr = params.row.goodDetail.name
            return h('div', resultStr)
          }
        },
        {
          title: '图片',
          key: 'img',
          align: 'center',
          width: 86,
          render: (h, params) => {
            return h('div', [
              h('img', {
                attrs: {
                  src: params.row.goodDetail.imgUrls[0],
                  class: 'cartImg'
                },
                style: {
                  width: '50px'
                }
              })
            ])
          }
        },
        {
          title: '单价',
          width: 90,
          align: 'center',
          render: (h, params) => {
            let resultStr = ''
            resultStr = params.row.goodDetail.price
            return h('div', resultStr)
          }
        },
        {
          title: '数量',
          key: 'qty',
          width: 250,
          align: 'center',
          render: (h, params) => {
            let resultStr = ''
            resultStr = params.row.qty
            return h('div', resultStr)
          }
        },
        {
          title: '该商品总价',
          align: 'center',
          render: (h, params) => {
            let resultStr = ''
            resultStr = params.row.qty * params.row.goodDetail.price
            return h('div', resultStr)
          }
        }
      ],
      checkCoupon: {
        choose: '未选择',
        name: '优惠'
      },
      checkPromotion: {
        choose: '未选择',
        name: '促销'
      },
      // 备注信息
      remarks: '',
      // 商品信息
      shoppingCart: [{
        goodId: 0,
        qty: 1,
        goodDetail: {
          price: 0,
          imgUrls: [''],
          name: ''
        }
      }],
      // 原价格
      originPrice: 0,
      // 折扣
      discountPrice: 0,
      // 满足的满减活动列表
      coupons: [
      ],
      promotions: [],
      uid: -1,
      endPrice: null,
      promotionType: '',
      idList: [],
      loading: true
    }
  },
  computed: {
    totalPrice() {
      if (this.endPrice !== null) {
        return this.endPrice
      } else { return this.originPrice - this.discountPrice }
    }
  },
  methods: {
    // 选择优惠券
    changeCoupon(data) {
      const item = this.coupons[data]
      this.checkCoupon.name = item.couponName + ':' + item.threshold + '-' + item.discount_price
      this.checkCoupon.choose = '已选择'
      this.discountPrice = parseInt(item.discount_price)
      // 如果先选择了促销又来点击优惠券，那就先获取原价减去优惠券，再发送请求重新计算促销活动后的价格
      if (this.endPrice !== null) {
        const price = this.originPrice - this.discountPrice
        usePromotion(this.promotionType, price, this.idList).then(res => {
          if (res.data.zhekouhouPrice) {
            this.endPrice = res.data.zhekouhouPrice
          } else {
            this.endPrice = res.data
          }
        })
      }
    },
    // 选择商品促销
    changePromotion(data) {
      this.checkPromotion.name = data
      this.checkPromotion.choose = '已选择'
      this.promotionType = data
      const price = this.originPrice - this.discountPrice
      usePromotion(data, price, this.idList).then(res => {
        if (res.data.zhekouhouPrice) {
          this.endPrice = res.data.zhekouhouPrice
        } else {
          this.endPrice = res.data
        }
      })
    },
    // 点击付款
    gotoPay() {
      // 请求的参数
      const body = {
        payType: 0,
        memberId: this.uid,
        receiverName: this.$store.state.user.userInfo.username,
        memberUsername: this.$store.state.user.userInfo.username,
        receiverPhone: this.$store.state.user.userInfo.phone,
        deleteStatus: 0,
        status: 0,
        orderItemList: [
        ],
        cartIds: [],
        totalAmount: this.originPrice,
        couponAmount: this.originPrice - this.totalPrice,
        payAmount: this.totalPrice.toFixed(2)
      }
      // 为body的商品列表添加信息
      this.shoppingCart.forEach(e => {
        const value = {
          productId: e.goodId,
          productName: e.goodDetail.name,
          productPrice: e.goodDetail.price,
          productQuantity: e.qty,
          productPic: e.goodDetail.imgUrls[0],
          productSkuId: e.goodDetail.brandId
        }
        body.orderItemList.push(value)
      })
      generateOrder(body).then(res => {
        if (res.code === 200) {
          // 进入付款状态，就删除购物车相关。（正在结算的表在页面离开时删除）
          deleteShoppingCart(this.idList, this.uid)
          // 为订单付款
          this.$router.push('/payDone')
        }
      })
    }
  },
  async created() {
    this.uid = this.$store.state.user.userInfo.uid
    // 获取用户正在结算的商品id（idList）
    await getOrding(this.uid).then(res => {
      const resultList = JSON.parse(res.data.goodsId)
      resultList.forEach(e => {
        this.idList.push(parseInt(e.goodId))
      })
    })
    // 根据商品id列表获取商品信息
    await getGoodsBatch(this.uid, this.idList).then(res => {
      this.shoppingCart = res.data
      this.shoppingCart.forEach(e => {
        this.originPrice += e.qty * e.goodDetail.price
      })
      this.loading = false
    })
    // 获取优惠信息
    queryCoupon(this.uid, this.originPrice).then(res => {
      res.data.forEach(e => {
        this.coupons.push({
          couponName: e.couponName,
          threshold: e.threshold,
          discount_price: e.discount_price
        })
      })
    })
    // 获取促销信息
    queryPromotion(this.idList).then(res => {
      res.data.forEach(e => {
        this.promotions.push(e)
      })
    })
  },
  // 离开页面，都需要删除结算表
  beforeDestroy() {
    deleteOrding(this.uid)
  },
  components: {
    Search,
    GoodsListNav
  }
}
</script>

<style scoped>
.goods-list-container {
  margin: 15px auto;
  width: 80%;
}
.tips-box {
  margin-bottom: 15px;
}
.address-container {
  margin-top: 15px;
}
.address-box {
  margin-top: 15px;
  padding: 15px;
  border: 1px #ccc dotted;
}
.address-check {
  margin: 15px 0px;
  height: 36px;
  display: flex;
  align-items: center;
}
.address-check-name {
  width: 120px;
  display: flex;
  justify-content: center;
  align-content: center;
  background-color: #ccc;
}
.address-check-name span {
  width: 120px;
  height: 36px;
  font-size: 14px;
  line-height: 36px;
  text-align: center;
  color: #fff;
  background-color: #f90013;
}
.address-detail {
  padding-left: 15px;
  font-size: 14px;
  color: #999999;
}
.remarks-container {
  margin: 15px 0px;
}
.remarks-input {
  margin-top: 15px;
}
.invoices-container p {
  font-size: 12px;
  line-height: 30px;
  color: #999;
}
.pay-container {
  margin: 15px;
  display: flex;
  justify-content: flex-end;
}
.pay-box {
  font-size: 18px;
  font-weight: bolder;
  color: #495060;
}
.money {
  font-size: 26px;
  color: #f90013;
}
.pay-btn {
  margin: 15px 0px;
  display: flex;
  justify-content: flex-end;
}
</style>
